//
//  Click Link or Button in Current Webpage.m
//  Click Link or Button in Current Webpage
//
//  Created by itod on 3/30/07.
//  Copyright 2007 Todd Ditchendorf. All rights reserved.
//

#import "Click Link or Button in Current Webpage.h"

typedef enum {
	ClickedItemTypeHTMLLink = 0,
	ClickedItemTypeHTMLButton,
	ClickedItemTypeBrowserBackButton,
	ClickedItemTypeBrowserForwardButton,
	ClickedItemTypeBrowserReloadButton
} ClickedItemType;

@interface Click_Link_or_Button_in_Current_Webpage (Private)
- (NSString *)pathForJavaScriptResource:(NSString *)filename;
@end

@implementation Click_Link_or_Button_in_Current_Webpage

#pragma mark -
#pragma mark AbstractMethods

- (NSString *)javaScriptSource
{
	NSString *elementIdentifier = [self objectForParameterKey:@"elementIdentifier"];

	NSString *filename = nil;
	NSMutableString *jsSource = nil;
	NSString *tagName = nil;

	int clickedItemType	= [[self objectForParameterKey:@"clickedItemType"] intValue];

	switch (clickedItemType) {

		case ClickedItemTypeHTMLLink:
			filename = ([self isIdSelected]) ? @"ClickElementWithId" : @"ClickElementWithText";
			jsSource = [NSString stringWithContentsOfFile:[self pathForJavaScriptResource:filename]];	
			tagName = @"a";
			jsSource = [NSString stringWithFormat:jsSource, tagName, elementIdentifier];
			break;

		case ClickedItemTypeHTMLButton:
			filename = ([self isIdSelected]) ? @"ClickElementWithId" : @"ClickElementWithText";
			jsSource = [NSString stringWithContentsOfFile:[self pathForJavaScriptResource:filename]];	
			tagName = @"button";
			jsSource = [NSString stringWithFormat:jsSource, tagName, elementIdentifier];
			break;
			
		case ClickedItemTypeBrowserBackButton:
			filename = @"ClickBrowserBackButton";
			jsSource = [NSString stringWithContentsOfFile:[self pathForJavaScriptResource:filename]];	
			break;
			
		case ClickedItemTypeBrowserForwardButton:
			filename = @"ClickBrowserForwardButton";
			jsSource = [NSString stringWithContentsOfFile:[self pathForJavaScriptResource:filename]];	
			break;
			
		case ClickedItemTypeBrowserReloadButton:
			filename = @"ClickBrowserReloadButton";
			jsSource = [NSString stringWithContentsOfFile:[self pathForJavaScriptResource:filename]];	
			break;
			
	}
	
	jsSource = [NSMutableString stringWithString:jsSource];
	[jsSource replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:nil range:NSMakeRange(0, [jsSource length])];

	//NSLog(@"jsSource: %@", jsSource);

	return jsSource;
}


- (NSString *)pathForJavaScriptResource:(NSString *)filename
{	
	NSBundle *bundle = [NSBundle bundleForClass:[self class]];
	return [bundle pathForResource:filename ofType:@"js" inDirectory:@"JavaScript"];
}

@end
